<template>
  <div class="app-container">

    <!--搜索表单-->
    <el-form :inline="true" :model="searchOldhouse" class="demo-form-inline">
      <el-form-item label="标题">
        <el-input
          v-model="searchOldhouse.title"
          clearable
          placeholder="请输入标题"
        />
      </el-form-item>
      <el-form-item label="小区">
        <el-select v-model="searchOldhouse.estateId" clearable placeholder="请选择">
          <el-option
            v-for="item in estateList"
            :key="item.value"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="放盘日期">
        <el-date-picker
          v-model="entrydate"
          clearable
          value-format="yyyy-MM-dd"
          type="daterange"
          placeholder="选择日期"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 400px; margin-left: 20px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>

    <!--按钮-->
    <el-row>
      <el-button type="danger" size="medium" @click="deleteByIds">- 批量删除</el-button>
      <el-button type="primary" size="medium" @click="action = '新增';oldhouse = { houseImages: '' };dialogVisible = true">+
        新增
      </el-button>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog
      ref="form"
      :title="action"
      :visible.sync="dialogVisible"
      :before-close="reset"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="80%"
    >
      <el-form ref="form" :model="oldhouse" label-width="80px" size="mini">
        <el-form-item label="标题">
          <el-input v-model="oldhouse.title" autofocus style="width:60%" />
          房源状态
          <el-select v-model="oldhouse.state" placeholder="请选择" value-key="oldhouse.state" style="width:15%">
            <el-option
              v-for="item in stateList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="小区">
          <el-select v-model="oldhouse.estateId" placeholder="请选择" style="width:25%">
            <el-option
              v-for="item in estateList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
<!--            <el-option v-if="estateList.filter(function(e){ return e.id == oldhouse.estateId}).length == 0 " :key="oldhouse.estateId" label="未知" :value="oldhouse.estateId" />-->
          </el-select>
          朝向
          <el-select v-model="oldhouse.houseDir" placeholder="请选择" value-key="oldhouse.houseDir" style="width:25%">
            <el-option
              v-for="item in houseDirList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          楼层
          <el-input v-model="oldhouse.houseFloor" placeholder="请输入" style="width:10%"/>
          共
          <el-input v-model="oldhouse.houseFloorTotal" placeholder="请输入" style="width:10%"/>层
        </el-form-item>
        <el-form-item label="装修">
          <el-select v-model="oldhouse.houseFitment" placeholder="请选择" value-key="oldhouse.houseFitment" style="width:25%">
            <el-option
              v-for="item in houseFitmentList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          面积
          <el-input v-model="oldhouse.houseArea" placeholder="请输入面积" value-key="oldhouse.houseArea" style="width:25%" />
          价格
          <el-input v-model="oldhouse.housePrice" placeholder="请输入价格" value-key="oldhouse.housePrice" style="width:25%" />
        </el-form-item>

        <el-form-item label="放盘日期">
          <el-date-picker
            v-model="oldhouse.houseTime"
            style="width: 25%"
            clearable
            type="date"
            placeholder="选择日期"
            size="small"
          />
<!--          押金
          <el-select v-model="oldhouse.houseDeposit" value-key="oldhouse.houseDeposit" placeholder="请选择" style="width:15%">
            <el-option
              v-for="item in houseDepositList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>-->
          户型
          <el-select v-model="oldhouse.houseShi" placeholder="0" value-key="oldhouse.houseShi" style="width:10%">
            <el-option
              v-for="n in 10"
              :key="n"
              :value="n"
            />
          </el-select>
          室
          <el-select v-model="oldhouse.houseTing" placeholder="0" value-key="oldhouse.houseTing" style="width:10%">
            <el-option
              v-for="n in 10"
              :key="n"
              :value="n"
            />
          </el-select>
          厅
          <el-select v-model="oldhouse.houseWei" placeholder="0" value-key="oldhouse.houseWei" style="width:10%">
            <el-option
              v-for="n in 2"
              :key="n"
              :value="n"
            />
          </el-select>
          卫
        </el-form-item>

        <el-form-item label="房源详情">
          <el-input v-model="oldhouse.houseInfo" show-word-limit type="textarea" rows="10" placeholder="请输入房源详情" />
        </el-form-item>

        <el-form-item label="房屋图片">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :headers="token"
            name="image"
            list-type="picture-card"
            :file-list="fileList"
            :limit="10"
            :auto-upload="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <el-dialog :visible.sync="imageVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="add">提交</el-button>
          <el-button @click="reset">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <br>
    <!--表格-->
    <template>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        border
        :row-style="rowStyle"
        :header-cell-style="{'background':'#dfdfdf','color':'black'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="estateName" label="小区" align="center">
          <template slot-scope="scope">
            <span style="margin-right: 10px">
              {{ estateList.filter(function(e){ return e.id == scope.row.estateId}).length == 1 ? scope.row.estateName : '未知' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" align="center" />
        <el-table-column prop="houseShi,houseTing,houseWei" label="户型" align="center">
          <template slot-scope="scope">
            {{ scope.row.houseShi }}室{{ scope.row.houseTing }}厅{{ scope.row.houseWei }}卫
          </template>
        </el-table-column>
        <el-table-column prop="housePrice" label="价格" align="center" />
        <el-table-column prop="houseFloor" label="楼层" align="center" />
        <el-table-column prop="houseArea" label="面积" align="center" />
        <el-table-column prop="houseImages" label="图片" align="center">
          <template slot-scope="{ row }">
            <el-image style="width: auto; height: 40px; border: none; cursor: pointer" :src="row.houseImages" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <span style="margin-right: 10px">
              {{ scope.row.state == '1' ? '出售中' : '已下架' }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="朝向">
          <template slot-scope="scope">
            <span v-if="scope.row.houseDir == 1" style="margin-right: 10px">东</span>
            <span v-if="scope.row.houseDir == 2" style="margin-right: 10px">南</span>
            <span v-if="scope.row.houseDir == 3" style="margin-right: 10px">西</span>
            <span v-if="scope.row.houseDir == 4" style="margin-right: 10px">北</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="放盘日期">
          <template slot-scope="scope">
            {{ scope.row.houseTime ? scope.row.houseTime.replace('T', ' ') : '' }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="更新日期">
          <template slot-scope="scope">
            {{ scope.row.updateTime ? scope.row.updateTime.replace('T', ' ') : '' }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="update(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :cursell-page="cursellPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @cursell-change="handleCursellChange"
    />
  </div>
</template>

<script>
import { page, add, update, deleteById, selectById, deleteImages } from '@/api/oldhouse.js'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      admin: null,
      dialogImageUrl: '',
      imageVisible: false,
      disabled: false,

      background: true,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,
      // 当前页码
      cursellPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 品牌模型数据
      searchOldhouse: {
        title: '',
        estateId: ''
      },
      oldhouse: {
        image: ''
      },
      estateList: [],
      stateList: envConfig.houseSetting.stateList,
      houseFitmentList: envConfig.houseSetting.houseFitmentList,
      houseDirList: envConfig.houseSetting.houseDirList,
      houseDepositList: envConfig.houseSetting.houseDepositList,

      beginTime: '',
      endTime: '',
      entrydate: '',

      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      token: { token: getToken() },
      action: '新增',
      fileList: [],
      oldhouseImage: []
    }
  },

  watch: {
    entrydate(val) {
      if (val && val.length >= 2) {
        this.beginTime = val[0]
        this.endTime = val[1]
      } else {
        this.beginTime = ''
        this.endTime = ''
      }
    }
  },

  mounted() {
    this.GLOBAL.getAdmin().then((res) => {
      this.admin = res
    })
    this.GLOBAL.getEstate().then((res) => {
      this.estateList = res
    })
    this.page() // 当页面加载完成后，发送异步请求，获取数据
  },

  methods: {
    rowStyle(row) {
      if (row.row.state === 0) {
        return { 'color': 'darkgray', 'text-decoration': 'line-through' }
      }
    },

    // 查询分页数据
    page() {
      page(
        this.searchOldhouse.title,
        this.searchOldhouse.estateId,
        this.beginTime,
        this.endTime,
        this.cursellPage,
        this.pageSize
      ).then((res) => {
        this.totalCount = res.data.data.total
        this.tableData = res.data.data.rows
      })
    },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 查询方法
    onSubmit() {
      this.cursellPage = 1
      this.page()
    },

    clear() {
      this.searchOldhouse = { title: '', estateId: ''}
      this.beginTime = ''
      this.endTime = ''
      this.entrydate = ''
      this.page()
    },
    reset() {
      this.fileList = []
      this.oldhouseImage = []
      this.dialogVisible = false
    },
    handleRemove(file, fileList) {
      const obj = this.fileList.find(item => item.uid === file.uid)
      const index = this.fileList.indexOf(obj)
      this.fileList.splice(index, 1)
      this.oldhouseImage.splice(index, 1)

      const imagesList = []
      imagesList.push(file.url.replace(process.env.VUE_APP_URL, ''))
      deleteImages(imagesList)
    },
    handlePictureCardPreview(file) {
      document.querySelector('.el-dialog__wrapper').setAttribute('style', 'z-index:9999')
      this.dialogImageUrl = file.url
      this.imageVisible = true
    },
    // 添加数据
    add() {
      let operator
      this.oldhouse.houseImages = this.oldhouseImage.join()
      if (this.oldhouse.id) {
        // 修改
        this.action = '编辑'
        operator = update(this.oldhouse)
      } else {
        this.oldhouse.adminId = this.admin.id
        this.fileList = []
        this.action = '新增'
        operator = add(this.oldhouse)
      }

      operator.then((resp) => {
        if (resp.data.code === 1) {
          this.oldhouseImage = []
          this.fileList = []
          this.dialogVisible = false
          this.page()
          this.$message({ message: '恭喜你，保存成功', type: 'success' })
          this.oldhouse = { houseImages: '' }
          this.oldhouseImage = []
        } else {
          this.$message.error(resp.data.msg)
        }
      })
    },
    update(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      this.action = '编辑'
      this.oldhouseImage = []
      this.fileList = []
      // 2. 发送请求

      selectById(id).then((result) => {
        if (result.data.code === 1) {
          this.oldhouse = result.data.data
          if (result.houseImagesArr) {
            this.fileList = result.houseImagesArr
            this.oldhouseImage = this.oldhouse.houseImages.split(',')
          }
        }
      })
    },

    // 删除信息
    deleteById(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 2. 发送AJAX请求
        deleteById(id).then((resp) => {
          if (resp.data.code === 1) {
            // 删除成功
            this.$message.success('恭喜你，删除成功')
            this.page()
          } else {
            this.$message.error(resp.data.msg)
          }
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    // 批量删除信息
    deleteByIds() {
      // 弹出确认提示框
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确认按钮
        // 1. 创建id数组, 从 this.multipleSelection 获取即可
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.selectedIds[i] = this.multipleSelection[i].id
        }

        // 2. 发送AJAX请求
        deleteById(this.selectedIds).then((resp) => {
          if (resp.data.code === 1) {
            // 删除成功
            this.$message.success('恭喜你，删除成功')
            this.page()
          } else {
            this.$message.error(resp.data.msg)
          }
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    // 文件上传相关
    handleAvatarSuccess(res, file, fileList) {
      this.fileList.push({ name: this.fileList.length, url: envConfig.uploadPath + res.data })
      this.oldhouseImage.push(res.data)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt500K = file.size / 1024 < 500
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isLt500K) {
        this.$message.error('上传头像图片大小不能超过 500KB!')
      }
      return isJPG && isLt500K
    },

    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCursellChange(val) {
      // 重新设置当前页码
      this.cursellPage = val
      this.page()
    }
  }
}
</script>

